package cn.sirun.com.fca.personal.center.view.impl;

import android.app.Activity;
import android.content.Intent;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.jungly.gridpasswordview.GridPasswordView;
import com.tencent.cloud.iov.common.flow.view.impl.BaseLoadingFlowView;
import com.tencent.cloud.iov.flow.view.IContentViewContainer;
import com.tencent.cloud.iov.kernel.constant.StatusCode;
import com.tencent.cloud.iov.kernel.model.BaseResponse;
import com.tencent.cloud.iov.router.Router;
import com.tencent.cloud.iov.util.ActivityUtils;
import com.tencent.cloud.iov.util.PatternMatchingUtils;
import com.tencent.cloud.iov.util.ResourcesUtils;
import com.tencent.cloud.iov.util.lifecycle.ActivityStackManager;
import com.tencent.cloud.uikit.utils.DialogUtils;
import com.tencent.cloud.uikit.utils.SystemUiUtils;

import java.lang.ref.WeakReference;

import cn.sirun.com.fca.account.R;
import cn.sirun.com.fca.account.constant.AccountActivityConst;
import cn.sirun.com.fca.account.constant.AccountIntentConst;
import cn.sirun.com.fca.account.constant.AccountStatusCode;
import cn.sirun.com.fca.account.constant.CaptchaConst;
import cn.sirun.com.fca.account.constant.RequestParamConst;
import cn.sirun.com.fca.account.model.base.SubmitPhoneRequest;
import cn.sirun.com.fca.account.model.base.SubmitPhoneResponse;
import cn.sirun.com.fca.account.model.register.RegisterSubmitResponse;
import cn.sirun.com.fca.account.uitl.AccountStatusUtils;
import cn.sirun.com.fca.account.uitl.CountDownHandler;
import cn.sirun.com.fca.account.uitl.CountDownRunnable;
import cn.sirun.com.fca.personal.center.constant.PersonalCenterIntentConst;
import cn.sirun.com.fca.personal.center.model.request.ChangeAccountResendRequest;
import cn.sirun.com.fca.personal.center.model.request.SubmitPhonePinRequest;
import cn.sirun.com.fca.personal.center.model.response.SubmitCodeResponse;
import cn.sirun.com.fca.personal.center.model.service.PersonalInfoManager;
import cn.sirun.com.fca.personal.center.presenter.IChangeRegisterAccountPresenter;
import cn.sirun.com.fca.personal.center.presenter.impl.ChangeRegisterAccountPresenter;
import cn.sirun.com.fca.personal.center.view.ICaptchaView;

public class CaptchaFlowView extends BaseLoadingFlowView<IChangeRegisterAccountPresenter>
        implements ICaptchaView {

    private TextView mPromptTV, mResendTV;
    private ImageView mErrorIV;
    private GridPasswordView mCaptchaGPV;

    private String mPhoneNumber;
    private int mFrom;
    private int mCountDown = 0;
    private CountDownHandler mCountDownHandler;
    private String mCaptchaCountDown;
    private String mResendCaptcha;
    private CaptchaRunnable mCaptchaRunnable;
    private String mSendString = "";
    private boolean mIsPhone;

    public CaptchaFlowView(Activity activity) {
        super(activity);
    }

    public CaptchaFlowView(Activity activity, IContentViewContainer container) {
        super(activity, container);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        setUpActionBar();
        initView();
    }

    private void setUpActionBar() {
        final Activity activity = getActivity();
        SystemUiUtils.showActionBar(activity, "");
    }

    @Override
    public void onChangeAccountResendResult(BaseResponse<SubmitPhoneResponse> response) {
        int code = response.getCode();
        if (code == StatusCode.SUCCESS) {
            mCountDown = CaptchaConst.COUNT_DOWN;
            if (null != response.getData()) {
                mCountDown = response.getData().getResendTime();
            }
        } else {
            handleCaptchaErrorCode(code);
        }
    }

    private void handleCaptchaErrorCode(int code) {
        if (AccountStatusCode.SMS_CAPTCHA_ERROR == code) {
            mResendTV.setText(ResourcesUtils.getString(R.string.tv_title_error_captcha));
            mErrorIV.setVisibility(View.GONE);
            return;
        }
        AccountStatusUtils.showToast(getActivity(), code);
    }

    @Override
    public void onChangeAcccountSubmitCaptchaResult(BaseResponse<RegisterSubmitResponse> reponse) {
        hideLoadingView();
        int code = reponse.getCode();
        if (code == StatusCode.SUCCESS) {

            if (mFrom == AccountIntentConst.MODIFY_REGISTER_ACCOUNT) {
                PersonalInfoManager.getInstance()
                        .updatePhoneInfo(RequestParamConst.DEFAULT_NATION_CODE, mPhoneNumber);
            } else {
                PersonalInfoManager.getInstance().updateEmail(mPhoneNumber);
            }
            ActivityStackManager.getInstance().clearNumberStack(5);
            return;
        }
        AccountStatusUtils.showToast(getActivity(), code);
    }

    @Override
    public void submitPhonePinResult(BaseResponse<RegisterSubmitResponse> response) {
        int code = response.getCode();
        if (code == StatusCode.SUCCESS) {

        }
    }

    @Override
    public void submitCodeVerifyResult(BaseResponse<SubmitCodeResponse> response) {
        int code = response.getCode();
        if (code == StatusCode.SUCCESS) {
            Intent pinIntent = Router.fromPath(AccountActivityConst.Path.SETTING_PIN);
            ActivityUtils.startActivityForResult(getActivity(), pinIntent);
        }else{
            DialogUtils.showToast(getActivity(), R.string.tv_title_error_captcha);
        }


    }

    @Override
    protected IChangeRegisterAccountPresenter createPresenter() {
        return new ChangeRegisterAccountPresenter();
    }

    private void initView() {
        setContentView(R.layout.other_captcha_activity);
        final Activity activity = getActivity();
        mPromptTV = activity.findViewById(R.id.tv_prompt_account);
        mResendTV = activity.findViewById(R.id.tv_count_resend_promt);
        mErrorIV = activity.findViewById(R.id.iv_error_prompt);
        mCaptchaGPV = activity.findViewById(R.id.gpv_captcha);

        mCaptchaGPV.setOnPasswordChangedListener(new GridPasswordView.OnPasswordChangedListener() {

            @Override
            public void onTextChanged(String psw) {

            }

            @Override
            public void onInputFinish(String psw) {
                if (mFrom == AccountIntentConst.FORGET_ACCOUNT_PIN) {

                    /**
                     * 校验忘记密码验证码
                     */

                    getPresenter().submitPinVerifyCaptcha(psw);
                } else{
                    showLoadingView();
                    if (mFrom == AccountIntentConst.MODIFY_REGISTER_ACCOUNT
                            || mFrom == AccountIntentConst.MOIDFY_BIND_ACCOUNT) {
                        getPresenter().changeAccountSubmitCaptcha(psw);
                    } else {
                        getPresenter().submitBindAccountCaptcha(psw);
                    }
                }
            }
        });

        mResendTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handleResendClick();
            }
        });

        initData(activity);
    }


    private void handleResendClick() {
        if (mFrom == AccountIntentConst.MODIFY_REGISTER_ACCOUNT) {
            ChangeAccountResendRequest request = null;
            if (mIsPhone) {
                request =
                        new ChangeAccountResendRequest(RequestParamConst.DEFAULT_NATION_CODE, mPhoneNumber);
            }
            getPresenter().changeAccountResend(request);
        } else if(mFrom == AccountIntentConst.FORGET_ACCOUNT_PIN){
            sendPinPhone();
        } else {
            getPresenter().bindAccountResend();
        }
        mResendTV.setEnabled(false);
        mCaptchaRunnable.setCountDown(mCountDown);
        mCountDownHandler.sendMessage(new Message());
    }

    private void initData(Activity activity) {
        Intent intent = activity.getIntent();
        mFrom = intent.getIntExtra(AccountIntentConst.FROM, AccountIntentConst.UNKNOWN);

        mCountDown = intent.getIntExtra(AccountIntentConst.COUNT_DOWN, CaptchaConst.COUNT_DOWN);
        if (intent.hasExtra(AccountIntentConst.TELEPHONE)) {
            mPhoneNumber = intent.getStringExtra(AccountIntentConst.TELEPHONE);
        }
        mIsPhone = PatternMatchingUtils.isTelephoneCorrect(mPhoneNumber);
        mCaptchaRunnable = new CaptchaRunnable(this, mCountDown);
        mCountDownHandler = new CountDownHandler(mCaptchaRunnable);
        mCountDownHandler.sendMessage(new Message());

        mCaptchaCountDown = ResourcesUtils.getString(R.string.tv_title_countdown_captcha);
        mResendCaptcha = ResourcesUtils.getString(R.string.tv_title_repeat_captcha);
        mIsPhone = PatternMatchingUtils.isTelephoneCorrect(mPhoneNumber);

        if (mFrom == AccountIntentConst.REGISTER) {
            if (mIsPhone) {
                mSendString =
                        String.format(ResourcesUtils.getString(R.string.tv_title_send_captcha), mPhoneNumber);
            } else {
                mSendString =
                        String.format(ResourcesUtils.getString(R.string.tv_title_send_captcha_emial), mPhoneNumber);
            }
        }else if(mFrom == AccountIntentConst.FORGET_ACCOUNT_PIN){
            sendPinPhone();
        }
        mPromptTV.setText(mSendString);
        mCaptchaGPV.togglePasswordVisibility();
    }

    private void sendPinPhone(){
        SubmitPhoneRequest request = new SubmitPhoneRequest();

        request.setNation("86");
        request.setPhone(PersonalInfoManager.getInstance().getPersonalInfo().getUserPhone());
//        request.setIdExist(PersonalInfoManager.getInstance().getPersonalInfo().isIdNumExist());
        request.setIdExist(false);
        getPresenter().submitPhonePin(request);
    }

    private static class CaptchaRunnable extends CountDownRunnable {

        private WeakReference<CaptchaFlowView> mCaptchaFlowView;

        public CaptchaRunnable(CaptchaFlowView captchaFlowView, int countDown) {
            super(countDown);
            mCaptchaFlowView = new WeakReference<>(captchaFlowView);
        }

        @Override
        public void run() {
            CaptchaFlowView captchaFlowView = mCaptchaFlowView.get();
            if (mCountDown > 0) {
                captchaFlowView.mResendTV.setText(
                        String.format(captchaFlowView.mCaptchaCountDown, mCountDown--));
                captchaFlowView.mResendTV.setTextColor(ResourcesUtils.getColor(R.color.grey_A8));
                captchaFlowView.mCountDownHandler.postDelayed(this, mInterval);
                captchaFlowView.mResendTV.setEnabled(false);
            } else {
                captchaFlowView.mResendTV.setText(captchaFlowView.mResendCaptcha);
                captchaFlowView.mResendTV.setTextColor(ResourcesUtils.getColor(R.color.login_register_text_color));
                captchaFlowView.mResendTV.setEnabled(true);
            }
        }
    }
}
